package com.bdqn.tour.dao.impl;



import com.bdqn.tour.dao.BaseDao;
import com.bdqn.tour.dao.HzyInvoiceDao;
import com.bdqn.tour.pojo.HzyInvoice;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class HzyInvoiceDaoImpl extends BaseDao implements HzyInvoiceDao {
    @Override
    public int addInvoice(HzyInvoice invoice) {
        conn = getConnection();
        String sql = "insert into invoice(type,invoice_Header,tin) values(?,?,?)";
        try {
            return executeUpdate(sql,
                    invoice.getType(),
                    invoice.getInvoice_Header(),
                    invoice.getTin()
            );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeAll(conn, psmt, rs);
        }
    }

    @Override
    public List<HzyInvoice> getInvoice(int pageNo, int pageSize) {
        List<HzyInvoice> list = new ArrayList<>();
        conn = getConnection();
        String sql = "select * from invoice limit ?,?";
        try {
            psmt = conn.prepareStatement(sql);
            psmt.setInt(1, (pageNo - 1) * pageSize);
            psmt.setInt(2, pageSize);
            rs = psmt.executeQuery();
            while (rs.next()) {
                HzyInvoice invoice = new HzyInvoice();
                invoice.setId(rs.getInt("id"));
                invoice.setType(rs.getString("type"));
                invoice.setInvoice_Header(rs.getString("invoice_Header"));
                invoice.setTin(rs.getString("tin"));
                list.add(invoice);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            closeAll(conn, psmt, rs);
        }
        return list;
    }

    @Override
    public int getInvoiceCount() {
        int totals = 0;
        conn = getConnection();
        String sql = "select count(*) from invoice";
        try {
            rs = executeQuery(sql);
            if (rs.next()) {
                totals = rs.getInt(1);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            closeAll(conn, psmt, rs);
        }

        return totals;
    }

    @Override
    public int delInvoice(int id) {
        int result = 0;
        conn = getConnection();
        String sql = "delete from invoice where id=?";
        try {
            result = executeUpdate(sql, id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            closeAll(conn, psmt, rs);
        }
        return result;
    }
}
